<template>
  <div class="app-container deposit-application-container-view">
    <div style="padding: 10px 0;">
      <DepositAppFormFilter
        @on-filter="submitFilterForm"
      />
    </div>
    <div class="button-group">
      <el-button
        v-if="roleCheck(paySetType.thirdRechargeAdd)" type="primary"
        size="mini"
        @click="openDialog({dialogName: dialogType.editDepositApp, props: {}})"
      >
        新增三方平台应用
      </el-button>
      <el-button
        v-if="roleCheck(paySetType.thirdRechargeStatusSet)" type="primary"
        size="mini"
        @click="toToggleDeposAppStatus(constType.escrowOpen)"
        :disabled="!isChecked"
      >
        批量上架
      </el-button>
      <el-button
        v-if="roleCheck(paySetType.thirdRechargeStatusSet)" type="primary"
        size="mini"
        @click="toToggleDeposAppStatus(constType.escrowClose)"
        :disabled="!isChecked"
      >
        批量下架
      </el-button>
    </div>
    <el-table
      border
      :data="tableData.list"
      v-loading="loading"
      element-loading-text="加载中..."
      class="el-table-align-center"
      :row-class-name="handleTableRowClassName"
      @selection-change="onChangeSelection"
    >
      <el-table-column
        type="selection"
        width="55"
      >
      </el-table-column>
      <!--<el-table-column label="通道号" prop="aisleName" align="center">
      </el-table-column>-->
      <el-table-column label="支付类型" prop="paymentName" align="center">
      </el-table-column>
      <el-table-column label="三方平台" prop="channelName" align="center">
        <template slot-scope="{row}">
          {{row.channelName}}
        </template>
      </el-table-column>
      <el-table-column label="商户号" prop="merchantCode" align="center">
        <template slot-scope="{row}">
          <el-tooltip
            placement="top"
            v-if="row.merchantCode && row.merchantCode.length > constType.ellipsisLen + 1"
          >
            <div slot="content" class="global-table-tooltip-item-view">
              {{row.merchantCode}}
            </div>
            <div class="global-table-single-item-view">{{row.merchantCode}}</div>
          </el-tooltip>
          <div class="global-table-single-item-view" v-else>{{row.merchantCode}}</div>
        </template>
      </el-table-column>
      <el-table-column label="渠道类型" prop="limitType" align="center">
        <template slot-scope="{row}">
          {{getLabel(row.limitType, payEnum.PAY_TYPE)}}
        </template>
      </el-table-column>
      <el-table-column label="层级类型" prop="levelName" width="160" align="center">
        <template slot-scope="{row}">
          <el-button
            type="text"
            @click="openDialog({dialogName: dialogType.levelDetails, props: row })"
          >
            {{row.levelName}}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="应用端" prop="clientType" align="center">
        <template slot-scope="{row}">
          {{getLabel(row.clientType, payEnum.DEVICE_TYPE)}}
        </template>
      </el-table-column>
      <el-table-column label="每日收款上限" prop="dailyLimit" align="center">
        <template slot-scope="{row}">
          {{row.dailyLimit | currency}}
        </template>
      </el-table-column>
      <el-table-column label="今日已收款金额" prop="successAmount" align="center">
        <template slot-scope="{row}">
          {{row.successAmount | currency}}
        </template>
      </el-table-column>
      <el-table-column label="推荐状态" prop="recommendStatus" align="center">
        <template slot-scope="{row}">
          {{getLabel(row.recommendStatus, payEnum.RECOMMEND_TYPE)}}
        </template>
      </el-table-column>
      <el-table-column label="上下架状态" prop="status" align="center">
        <template slot-scope="{row}">
          {{getLabel(row.status, payEnum.ESCROWS_STATUS_TYPE)}}
        </template>
      </el-table-column>
      <el-table-column label="置顶状态" prop="topStatus" align="center">
        <template slot-scope="{row}">
          {{getLabel(row.topStatus, payEnum.TOPPING_TYPE)}}
        </template>
      </el-table-column>
      <el-table-column label="开关状态" prop="openStatus" align="center">
        <template slot-scope="{row}">
          {{getLabel(row.openStatus, payEnum.PAY_STATUS_TYPE)}}
        </template>
      </el-table-column>
      <el-table-column label="最后修改人" prop="lastOperator" align="center"></el-table-column>
      <el-table-column label="最后修改时间" prop="lastUpdate" align="center" width="180">
        <template slot-scope="{row}">
          {{row.lastUpdate | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center">
      </el-table-column>
      <el-table-column label="操作"  width="220px" align="center" fixed="right">
        <template slot-scope="{row}">
          <el-button
            type="text"
            v-if="row.status === constType.escrowClose && roleCheck(paySetType.thirdRechargeStatusSet)"
            @click="onToggleDeposAppStatus(row, constType.escrowOpen)"
          >
            上架
          </el-button>
          <el-button
            type="text"
            v-else-if="row.status === constType.escrowOpen && roleCheck(paySetType.thirdRechargeStatusSet)"
            @click="onToggleDeposAppStatus(row, constType.escrowClose)"
          >
            下架
          </el-button>
          <span v-if="row.status === constType.escrowOpen || row.status === constType.escrowClose">
            <el-button
              v-if="roleCheck(paySetType.thirdRechargeEdit)"
              type="text"
              @click="openDialog({dialogName: dialogType.editDepositApp, props: row })"
            >
              编辑
            </el-button>
            <el-button
              v-if="roleCheck(paySetType.thirdRechargeDele)"
              type="text"
              @click="onClickDeleteItem(row)"
            >
              删除
            </el-button>
            <el-button
              type="text"
              @click="openDialog({
               dialogName: dialogType.confirmTopStatus,
               props: {
                  contentProps: constType.openTopping,
                  cacheData: { row, topStatus: constType.topStatusOpen },
               }
              })"
              v-if="row.topStatus === constType.topStatusClose && roleCheck(paySetType.thirdRechargeTopping) "
              >
              置顶
            </el-button>
            <el-button
              type="text"
              @click="openDialog({
                dialogName: dialogType.confirmTopStatus,
                props: {
                  contentProps: constType.closeTopping,
                  cacheData: { row, topStatus: constType.topStatusClose },
                }
              })"
              v-else-if="row.topStatus === constType.topStatusOpen && roleCheck(paySetType.thirdRechargeTopping)"
            >
              取消置顶
            </el-button>
            <el-button
              type="text"
              @click="openDialog({
                dialogName: dialogType.confirmRecoStatus,
                props: {
                  contentProps: constType.openRecommend,
                  cacheData: { row, recommendStatus: constType.recommendStatusOpen },
                }
              })"
              v-if="row.recommendStatus === constType.recommendStatusClose && roleCheck(paySetType.thirdRechargeRecomm) "
            >
              推荐
            </el-button>
            <el-button
              type="text"
              @click="openDialog({
                dialogName: dialogType.confirmRecoStatus,
                props: {
                  contentProps: constType.closeRecommend,
                  cacheData: { row, recommendStatus: constType.recommendStatusClose },
                }
              })"
              v-else-if="row.recommendStatus === constType.recommendStatusOpen && roleCheck(paySetType.thirdRechargeRecomm)"
            >
              取消推荐
            </el-button>
          </span>
          <span v-else>--</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="gridSizeChange"
        @current-change="gridCurrentChange"
        :current-page="filters.page"
        :page-sizes="gridPageSize"
        :page-size="filters.size"
        :layout="gridLayout"
        :total="tableData.total"
      >
      </el-pagination>
    </div>
    <EditDepositAppDialog
      v-if="dialogName === dialogType.editDepositApp"
      v-model="dialogVisible"
      :row-data="dialogProps"
      :id="dialogProps.id"
      @submit="submitFinished"
    />
    <LevelDetailsDialog
      v-if="dialogName === dialogType.levelDetails"
      v-model="dialogVisible"
      :row-data="dialogProps"
      :id="dialogProps.id"
      @submit="submitFinished"
    />
    <ConfirmStatusDialog
      v-if="dialogName === dialogType.confirmTopStatus"
      v-model="dialogVisible"
      :rowData="dialogProps"
      @confirm="onToggleTopStatus"
    />
    <ConfirmStatusDialog
      v-if="dialogName === dialogType.confirmRecoStatus"
      v-model="dialogVisible"
      :rowData="dialogProps"
      @confirm="onToggleRecoStatus"
    />
  </div>
</template>

<script>

// constants
import { messageType } from '@/const/enum';
import { constType } from '@/const/payEnum';
import { paySetType } from '@/router/payRoutes';

// components
import DepositAppFormFilter from './depositAppFormFilter';
import EditDepositAppDialog from './editDepositAppDialog';
import LevelDetailsDialog from './levelDetailsDialog';
import ConfirmStatusDialog from './confirmStatusDialog';

// services
import {
  getDepositApplicationList,
  deleteDepositApplication,
  updateDepositApplicationStatus,
  updateDepositApplicationTopping,
  updateDepositApplicationRecommend,
} from '@/services/api/payment';

// mixins
import {
  grid, form, dialog, constsLabel,
} from '@/build';

const dialogType = {
  editDepositApp: 'edit-deposit-app-dialog',
  levelDetails: 'level-details-dialog',
  confirmTopStatus: 'confirm-top-status-dialog',
  confirmRecoStatus: 'confirm-reco-status-dialog',
};

export default {
  name: 'depost-application',
  components: {
    DepositAppFormFilter,
    EditDepositAppDialog,
    LevelDetailsDialog,
    ConfirmStatusDialog,
  },
  mixins: [grid, form, dialog, constsLabel],
  data() {
    return {
      paySetType,
      filters: {
        page: 1,
        size: 20,
        levelIds: '',
      },
      tableData: {},
      dialogType,
      constType,
      tableSelectionList: [],
    };
  },
  computed: {
    isChecked() {
      return Array.isArray(this.tableSelectionList) && !!this.tableSelectionList.length;
    },
  },
  methods: {
    handleTableRowClassName({ row }) {
      const { dailyLimit, successAmount } = row || {};
      if (successAmount > dailyLimit) {
        return 'finished-row';
      }
      return '';
    },
    async onToggleDeposAppStatus({ id }, status, type = 1) {
      try {
        const display = status === constType.escrowOpen ? '上架' : '下架';
        const name = (type === 1 ? '' : '批量') + display;
        await this.$confirm(`确定要${name}${type === 1 ? '此' : '这些'}三方充值应用吗？`, `${name}三方充值应用`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        const [bool, result] = await updateDepositApplicationStatus({ merchantAppIds: id, status });
        if (!bool) throw new Error(result.message);
        this.gridSearch();
        this.$notify({
          type: 'success',
          message: `${display}成功`,
        });
      } catch (e) {
        if (e === messageType.cancel) return;
        this.$message({
          message: e.message,
          type: 'error',
        });
      }
    },
    async onClickDeleteItem({ id }) {
      try {
        await this.$confirm('确定要删除此三方充值应用吗？', '删除三方充值应用', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        const [bool, result] = await deleteDepositApplication({ id });
        if (!bool) throw new Error(result.message);
        this.gridSearch();
        this.$notify({
          type: 'success',
          message: '删除成功',
        });
      } catch (e) {
        if (e === messageType.cancel) return;
        this.$message({
          message: e.message,
          type: 'error',
        });
      }
    },
    async onToggleTopStatus({ row, topStatus }) {
      try {
        const [bool, result] = await updateDepositApplicationTopping({
          id: row.id,
          topStatus,
        });
        if (!bool) throw new Error(result.message);
        this.gridSearch();
        this.$notify({
          type: 'success',
          message: `${topStatus === constType.topStatusClose ? '取消' : ''}置顶成功`,
        });
      } catch (e) {
        if (e === messageType.cancel) return;
        this.$message({
          message: e.message,
          type: 'error',
        });
      }
    },
    async onToggleRecoStatus({ row, recommendStatus }) {
      try {
        const [bool, result] = await updateDepositApplicationRecommend({
          id: row.id,
          recommendStatus,
        });
        if (!bool) throw new Error(result.message);
        this.gridSearch();
        this.$notify({
          type: 'success',
          message: `${recommendStatus === constType.recommendStatusClose ? '取消' : ''}推荐成功`,
        });
      } catch (e) {
        if (e === messageType.cancel) return;
        this.$message({
          message: e.message,
          type: 'error',
        });
      }
    },
    onChangeSelection(val) {
      this.tableSelectionList = val;
    },
    toToggleDeposAppStatus(status) {
      const id = this.tableSelectionList.map(item => item.id).join(',');
      this.onToggleDeposAppStatus({ id }, status, 2);
    },
  },
  mounted() {
    // tab页记录访问日志
    this.$store.dispatch(types.SAVE_OPERATION_LOG, { content: _.getContent(this.$route, '三方入款应用', true) });
    const { level } = this.$route.query;
    if (level && !_.isUndefined(level)) {
      this.filters.levelIds = [Number(level)].join();
    }
    this.bindGet(getDepositApplicationList, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
    });
    this.getAll();
  },
};
</script>

<style lang="scss">
  .deposit-application-container-view {
    .el-table .finished-row {
      background: #ffc55b;
    }
  }
</style>
